package org.eiahe.hr.salary.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ehe.common.core.BaseController;
import org.ehe.common.core.domain.R;
import org.ehe.common.core.validate.AddGroup;
import org.ehe.common.core.validate.EditGroup;
import org.ehe.common.log.annotation.Log;
import org.ehe.common.log.enums.BusinessType;
import org.ehe.common.mybatis.core.page.PageQuery;
import org.ehe.common.mybatis.core.page.TableDataInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.eiahe.hr.salary.domain.bo.BonusPaymentBo;
import org.eiahe.hr.salary.domain.vo.BonusPaymentVo;
import org.eiahe.hr.salary.service.IBonusPaymentService;
import org.ehe.common.excel.utils.ExcelUtil;
import org.eiahe.hr.salary.domain.vo.BonusImportVo;
import org.ehe.common.excel.core.ExcelResult;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MultipartFile;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 奖金发放Controller
 *
 * @author zhangnn
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/salary/bonus")
@Slf4j
public class BonusPaymentController extends BaseController {

    private final IBonusPaymentService iBonusPaymentService;

    /**
     * 查询奖金发放列表
     */
    @SaCheckPermission("salary:bonus:list")
    @GetMapping("/list")
    public TableDataInfo<BonusPaymentVo> list(BonusPaymentBo bo, PageQuery pageQuery) {
        return iBonusPaymentService.queryPageList(bo, pageQuery);
    }

    /**
     * 获取奖金发放详细信息
     *
     * @param paymentId 主键
     */
    @SaCheckPermission("salary:bonus:query")
    @GetMapping("/{paymentId}")
    public R<BonusPaymentVo> getInfo(@PathVariable Long paymentId) {
        return R.ok(iBonusPaymentService.queryById(paymentId));
    }

    /**
     * 新增奖金发放
     */
    @SaCheckPermission("salary:bonus:add")
    @Log(title = "奖金发放", businessType = BusinessType.INSERT)
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody BonusPaymentBo bo) {
        return toAjax(iBonusPaymentService.insertByBo(bo));
    }

    /**
     * 修改奖金发放
     */
    @SaCheckPermission("salary:bonus:edit")
    @Log(title = "奖金发放", businessType = BusinessType.UPDATE)
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody BonusPaymentBo bo) {
        return toAjax(iBonusPaymentService.updateByBo(bo));
    }

    /**
     * 删除奖金发放
     *
     * @param paymentIds 主键串
     */
    @SaCheckPermission("salary:bonus:remove")
    @Log(title = "奖金发放", businessType = BusinessType.DELETE)
    @DeleteMapping("/{paymentIds}")
    public R<Void> remove(@PathVariable Long[] paymentIds) {
        return toAjax(iBonusPaymentService.deleteWithValidByIds(Arrays.asList(paymentIds)));
    }

    /**
     * 导入奖金数据
     */
    @SaCheckPermission("salary:bonus:import")
    @Log(title = "奖金发放", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public R<Void> importBonusData(@RequestParam("file") MultipartFile file) {
        try {
            // 解析Excel文件
            ExcelResult<BonusImportVo> excelResult = ExcelUtil.importExcel(file.getInputStream(), BonusImportVo.class,
                    true);
            List<BonusImportVo> dataList = excelResult.getList();
            List<String> errorList = excelResult.getErrorList();

            // 校验数据并保存
            iBonusPaymentService.importBonusData(dataList, errorList);

            int successCount = dataList.size() - errorList.size();
            int errorCount = errorList.size();

            return R.ok(String.format("导入完成，成功%d条，失败%d条", successCount, errorCount));
        } catch (Exception e) {
            log.error("导入奖金数据失败", e);
            return R.fail("导入失败：" + e.getMessage());
        }
    }

    /**
     * 下载导入模板
     */
    @SaCheckPermission("salary:bonus:import")
    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response) {
        try {
            String fileName = "奖金导入模板.xlsx";
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            ExcelUtil.exportTemplate(Collections.emptyList(), "excel/bonus_template.xlsx", response.getOutputStream());
        } catch (Exception e) {
            log.error("下载模板失败", e);
        }
    }

    /**
     * 导出奖金发放列表
     */
    @SaCheckPermission("salary:bonus:export")
    @Log(title = "奖金发放", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(BonusPaymentBo bo, HttpServletResponse response) {
        List<BonusPaymentVo> list = iBonusPaymentService.queryList(bo);
        ExcelUtil.exportExcel(list, "奖金发放数据", BonusPaymentVo.class, response);
    }

    /**
     * 发放奖金
     *
     * @param paymentId 奖金发放ID
     */
    @SaCheckPermission("salary:bonus:pay")
    @Log(title = "奖金发放", businessType = BusinessType.UPDATE)
    @PutMapping("/pay/{paymentId}")
    public R<Void> payBonus(@PathVariable Long paymentId) {
        return toAjax(iBonusPaymentService.payBonus(paymentId));
    }

    /**
     * 领取奖金
     *
     * @param paymentId 奖金发放ID
     */
    @SaCheckPermission("salary:bonus:receive")
    @Log(title = "奖金发放", businessType = BusinessType.UPDATE)
    @PutMapping("/receive/{paymentId}")
    public R<Void> receiveBonus(@PathVariable Long paymentId) {
        return toAjax(iBonusPaymentService.receiveBonus(paymentId));
    }
}
